const App = {
    mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            showDialog1: false,
            page: {
                activeName: 'first',
                value1: '',
                PageNumber: 1, //页码
                RowAmount: 10,
                Condition: window.btoa(unescape(encodeURIComponent("%%,%%"))),
                ExtensionCondition: ''
            },
            form: {},
            form1: {},
            showDialog2: false,
            blue_plate_self_built_house_type: [],
            personal_information: [],
            base_system_village: [],
            layer: {},
            loading2: false
        }
    },
    mounted() {

    },
    computed: {
        colors() {
            return function (row) {
                let arr = []
                if (row.Self_Built_Houses == '1') {
                    arr.push('#409EFF');
                }
                if (row.Plate_Type_SerialNumber == '居民户') {
                    arr.push('#67C23A');
                } else if (row.Plate_Type_SerialNumber == '商户') {
                    arr.push('#E6A23C');
                } else if (row.Plate_Type_SerialNumber == '企业') {
                    arr.push('#F56C6C');
                } else if (row.Plate_Type_SerialNumber == '党支部') {
                    arr.push('#7844a3');
                }
                if (arr.length == 1) {
                    return { backgroundColor: arr[0] }
                } else {
                    return { background: `linear-gradient(to right, ${arr.join(', ')})` }
                }
            }
        }
    },
    methods: {
        handleQH(row) {
            this.showDialog = true;
            const timer = setTimeout(() => {
                const qrElement = document.getElementById(`qr-img`);
                if (qrElement) qrElement.innerHTML = "";
                new QRious({
                    element: qrElement,
                    value: `${h5}blue_plate_detail/index.html?Blue_Plate_SerialNumber=${row.Blue_Plate_SerialNumber}`,
                    size: 120, // 增大尺寸到256px
                    level: "H", // 最高容错率（可恢复30%损坏）
                    background: "#ffffff", // 明确背景色
                    foreground: "#000000", // 明确前景色
                    quietZone: 1, // 增加空白边距
                });
                if (qrElement) {
                    qrElement.style.transition = "all 0.5s ease";
                    qrElement.style.opacity = "0";
                    setTimeout(() => {
                        qrElement.style.opacity = "1";
                    }, 100);
                }
                clearTimeout(timer);
            })
        },
        handleClick() {
            if (this.page.activeName == 'first') {
                this.page.ExtensionCondition = '';
            } else if (this.page.activeName == 'second') {
                this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent("AND blue_plate_information.Self_Built_Houses = '1'")));
            } else if (this.page.activeName == 'third') {
                this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent("AND blue_plate_information.Plate_Type_SerialNumber = '居民户'")));
            } else if (this.page.activeName == 'fourth') {
                this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent("AND blue_plate_information.Plate_Type_SerialNumber = '商户'")));
            } else if (this.page.activeName == 'fifth') {
                this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent("AND blue_plate_information.Plate_Type_SerialNumber = '企业'")));
            } else if (this.page.activeName == 'sixth') {
                this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent("AND blue_plate_information.Plate_Type_SerialNumber = '党支部'")));
            }
            this.postgetList(this.page);
        },
        Treedata() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/clientOperation/getDistrictTree`,
                type: "GET",
                data: {
                    DistrictCode: '232723'
                },
                success: (data) => {
                    this.treeData = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: "base_system_village",
                    Condition: "VillageNumber LIKE '232723%'",
                },
                success: (data) => {
                    this.base_system_village = data
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: "personal_information",
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.personal_information = data
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: "blue_plate_self_built_house_type",
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.blue_plate_self_built_house_type = data
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        check() {
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%,%%")));
            this.postgetList(this.page)
        },
        //树的点击筛选事件
        handleNodeClick(data, node) {
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + this.page.value1 + "%," + data.ProvinceNumber + "%")));
            // let arr = [], str = '';
            // if (data.children) {
            //     this.Organization(data.children, arr);
            // }
            // [data.Grid_SerialNumber, ...arr].forEach(item => {
            //     if (str) {
            //         str += "\r\nOR blue_plate_information.Grid_SerialNumber='" + item + "'";
            //     } else {
            //         str = "\r\nblue_plate_information.Grid_SerialNumber='" + item + "'";
            //     }
            // })
            // if (str) {
            //     str = "AND (" + str + ")"
            // }
            // this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(str)));
            this.postgetList(this.page)
        },
        Organization(data, arr) {
            data.forEach(item => {
                arr.push(item.Grid_SerialNumber);
                if (item.children && item.children.length > 0) {
                    this.Organization(item.children, arr);
                }
            })
        },
        population(row) {
            if (row.Unit_Quantity) {
                this.form = {}//初始化          
                this.form = row;
                if (row.Layer_JSON) {
                    this.layer = JSON.parse(row.Layer_JSON);
                }
                //若是正常楼，需要给每一户配置
                //若是自建房，需要给这个蓝牌配置
                this.showDialog1 = true;
            } else {
                this.$message({
                    message: '暂未关联房屋，请先关联房屋!',
                    type: 'warning'
                })
            }
        },
        handleRoom(row) {
            if (this.form.Self_Built_Houses == '0') {
                if (row.Live_Status == '1') {
                    window.location.href = 'add1.html?action=Modify&Blue_Plate_SerialNumber=' + row.Blue_Plate_SerialNumber
                        + "&House_Room_SerialNumber=" + row.House_Room_SerialNumber;
                } else {
                    window.location.href = 'add1.html?action=Add&Blue_Plate_SerialNumber=' + row.Blue_Plate_SerialNumber
                        + "&House_Room_SerialNumber=" + row.House_Room_SerialNumber;
                }
            } else {
                this.$message({
                    message: '检查当前蓝牌为自建房，点击下方按钮关联人口',
                    type: 'warning'
                })
            }
        },
        handleRoom1() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'blue_plate_house_room',
                    Condition: "Blue_Plate_SerialNumber = '" + this.form.Blue_Plate_SerialNumber + "' LIMIT 1",
                },
                success: (data) => {
                    if (data[0].Live_Status == '1') {
                        window.location.href = 'add1.html?action=Modify&Blue_Plate_SerialNumber=' + this.form.Blue_Plate_SerialNumber;
                    } else {
                        window.location.href = 'add1.html?action=Add&Blue_Plate_SerialNumber=' + this.form.Blue_Plate_SerialNumber;
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        handleHouse(row) {
            window.location.href = 'add2.html?action=Add&Blue_Plate_SerialNumber=' + row.Blue_Plate_SerialNumber;
        },
        selfbuilthouses(row) {
            if (row.Unit_Quantity && row.Layer_Quantity && row.Room_Quantity) {
                this.$confirm('检测到该蓝牌已关联房屋，该操作将会重置关联的房屋，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this.showDialog2 = true;
                    this.form1.Blue_Plate_SerialNumber = row.Blue_Plate_SerialNumber;
                    this.form1.Self_Built_House_Name = row.Blue_Plate_Name;
                }).catch(() => { });
            } else {
                this.showDialog2 = true;
                this.form1.Blue_Plate_SerialNumber = row.Blue_Plate_SerialNumber;
                this.form1.Self_Built_House_Name = row.Blue_Plate_Name;
            }
        },
        async validateAllForms() {
            //获取当前页面上所有的Elform
            let forms = [];
            for (let key in this.$refs) {
                const ref = this.$refs[key];
                if (ref.$options && ref.$options.name == 'ElForm') {
                    forms.push(ref);
                }
            }
            //判断每个Elform的校验是否通过
            let isfail = false;
            for (const form of forms) {
                try {
                    await form.validate();
                } catch (error) {
                    isfail = true;
                }
            }
            if (isfail) {
                return false;
            }
            return true;
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading2 = true;
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                    method: "post",
                    data: {
                        Data: JSON.stringify([{
                            tableName: 'blue_plate_information',
                            Condition: window.btoa(unescape(encodeURIComponent("Blue_Plate_SerialNumber='" + this.form1.Blue_Plate_SerialNumber + "'"))),
                        }, {
                            tableName: 'blue_plate_house_room',
                            Condition: window.btoa(unescape(encodeURIComponent("Blue_Plate_SerialNumber='" + this.form1.Blue_Plate_SerialNumber + "' AND Row_Status='0'"))),
                        }, {
                            tableName: 'blue_plate_house_holder',
                            Condition: window.btoa(unescape(encodeURIComponent("Blue_Plate_SerialNumber='" + this.form1.Blue_Plate_SerialNumber + "' AND Row_Status='0'"))),
                        }]),
                    },
                    success: ({ blue_plate_information, blue_plate_house_room, blue_plate_house_holder, blue_plate_person }) => {
                        blue_plate_information[0].Self_Built_Houses = '1'
                        let lJSONObject_DataSet = {
                            Add: {
                                blue_plate_self_built_house: [this.form1]
                            },
                            Modify: {
                                blue_plate_information,
                            }
                        }
                        if (blue_plate_house_room.length > 0) {
                            blue_plate_house_room.forEach(item => {
                                item.Row_Status = '1'
                            })
                            lJSONObject_DataSet['Modify']['blue_plate_house_room'] = blue_plate_house_room;
                        }
                        if (blue_plate_house_holder.length > 0) {
                            blue_plate_house_holder.forEach(item => {
                                item.Row_Status = '1'
                            })
                            lJSONObject_DataSet['Modify']['blue_plate_house_holder'] = blue_plate_house_holder;
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        if (!lJSONObject_DataSet['Add']) {
                            lJSONObject_DataSet['Add'] = new Object();
                        }
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: this.relativePath,
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]

                        submitSave(lJSONObject_DataSet, (res) => {
                            if (res.Status == 'success') {
                                this.showDialog2 = false
                                this.postgetList(this.page)
                            }
                            this.loading2 = false;
                            this.loading = false;
                        })
                        // $.ajax({
                        //     headers: requestHeaders("JSON"),
                        //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                        //     method: "post",
                        //     data: JSON.stringify({
                        //         Data: lJSONObject_DataSet,
                        //     }),
                        //     success: (res) => {
                        //         if (res.Status == 'success') {
                        //             this.showDialog2 = false
                        //             this.postgetList(this.page)
                        //         }
                        //     },
                        //     complete: (XMLHttpRequest) => {
                        //         this.loading = false;
                        //         requestPretreatment(XMLHttpRequest);
                        //     }
                        // });
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                });
            }
        }
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-house-grid', ylHouseGrid);
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
